package cn.lystudio.rohmtimeopwide_background_v11.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.lystudio.rohmtimeopwide_background_v11.entity.po.UsmZlRecordPO;
import cn.lystudio.rohmtimeopwide_background_v11.exceptions.JsonException;
import cn.lystudio.rohmtimeopwide_background_v11.mapper.UsmZlRecordPOMapper;
import cn.lystudio.rohmtimeopwide_background_v11.service.UsmZlRecordService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
@DS("master")

public class UsmZlRecordServiceImpl implements UsmZlRecordService {
    @Resource
    private UsmZlRecordPOMapper usmZlRecordPOMapper;
    @Override
    public int addRecord(UsmZlRecordPO usmZlRecordPO) {
        return usmZlRecordPOMapper.insert(usmZlRecordPO);
    }

    @Override
    public List<UsmZlRecordPO> getRecordByLotNo(String lotNo) {
        LambdaQueryWrapper<UsmZlRecordPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(UsmZlRecordPO::getLotNo,lotNo);
        return usmZlRecordPOMapper.selectList(wrapper);
    }

    @Override
    public UsmZlRecordPO getUsmZlRecordByID(Integer recordID) {
        return usmZlRecordPOMapper.selectById(recordID);
    }

    @Override
    public int uptRecord(UsmZlRecordPO usmZlRecordPO) {
        return usmZlRecordPOMapper.updateById(usmZlRecordPO);
    }

    @Override
    public int delRecord(Integer recordID) {
        return usmZlRecordPOMapper.deleteById(recordID);
    }

    @Override
    public List<UsmZlRecordPO> getList(String selectedMachineNo, String selectedDateFrom,String selectedDateTo) {
        return usmZlRecordPOMapper.selectList(new LambdaQueryWrapper<UsmZlRecordPO>()
                .eq(UsmZlRecordPO::getMachineNo,selectedMachineNo)
                .between(UsmZlRecordPO::getRecordTimeDT, selectedDateFrom,selectedDateTo)
        );
    }

    /**
     * 通过完整批次号,获取最新组立记录
     * @param fullLotNo
     * @return
     */
    @Override
    public UsmZlRecordPO getRecordByFullLotNo(String fullLotNo) {
        if(StrUtil.isEmpty(fullLotNo) || fullLotNo.length() != 12) throw new JsonException(500,"批次号错误");
        LambdaQueryWrapper<UsmZlRecordPO> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(UsmZlRecordPO::getLotNo,fullLotNo.substring(2,fullLotNo.length()-1))
            .orderByDesc(UsmZlRecordPO::getRecordTimeDT)
            .last("limit 1");
        UsmZlRecordPO usmZlRecordPO = usmZlRecordPOMapper.selectOne(wrapper);
        if(ObjectUtil.isEmpty(usmZlRecordPO)) throw new JsonException(500,"未找到批次号:"+fullLotNo+"的记录");
        return usmZlRecordPO;

    }
}
